#!/bin/bash

# 设置项目根目录
PROJECT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$PROJECT_DIR"

# 检查日志目录
if [ ! -d "logs" ]; then
    mkdir -p logs
    echo "Created logs directory"
fi

# 检查虚拟环境
VENV_DIR="cs_inven_fast_env"
if [ ! -d "$VENV_DIR" ]; then
    echo "Virtual environment not found. Please create it first."
    echo "Run: python -m venv $VENV_DIR"
    exit 1
fi

# 激活虚拟环境
source "$VENV_DIR/bin/activate"

# 检查依赖
pip install -r requirements.txt

# 明确设置为 dev 环境
ENV="dev"  # 直接硬编码为 dev
HOST="0.0.0.0"
PORT=8000

echo "Environment settings:"
echo "ENV: $ENV"
echo "HOST: $HOST"
echo "PORT: $PORT"

# 检查是否已运行
PID_FILE="logs/app.pid"
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p $PID > /dev/null 2>&1; then
        echo "Application is already running with PID: $PID"
        exit 1
    else
        rm "$PID_FILE"
    fi
fi

# 启动应用（确保使用正确的参数）
echo "Starting application in $ENV mode..."
nohup python run.py --env "dev" --host "$HOST" --port "$PORT" > logs/app.out 2>&1 &

# 保存PID
echo $! > "$PID_FILE"
echo "Application started with PID: $!"
echo "Logs available at logs/app.out"

# 等待几秒检查应用是否成功启动
sleep 3
if ! ps -p $! > /dev/null; then
    echo "Failed to start application. Check logs/app.out for details."
    exit 1
fi

echo "Application successfully started!"
